<?php
/**
 * Created by PhpStorm.
 * Author: Lin
 * Date: 2017/12/23
 * Time: 10:26
 */
namespace app\admin\controller;

use app\base\Tools;
use app\common\model\AdminMenus;
use think\Request;
use think\View;

class Menu extends BaseController
{
    //菜单管理
    public function index()
    {
        if ((Request::instance()->isAjax())) {
            $menuModel = new AdminMenus();
            $treeData = $menuModel->getMenuTree();
            $data['data'] = $treeData;
//            var_dump($data);die;
            return Tools::tableData($data);
        }
        return $this->fetch();
    }

    public function add(View $view)
    {
        $menuModel = new AdminMenus($this->param);
        $menuData = $menuModel->getList(['parent_id' => 0], 'menu_id, title')->toArray();
        $view->menuData = $menuData;

        if ((Request::instance()->isPost())) {
            if ($menuModel->allowField(true)->save()) {
                return Tools::ajaxReturn(true, '添加成功');
            } else {
                return Tools::ajaxReturn(false, '添加失败');
            }
        }
        return $this->fetch();
    }

    public function del()
    {
        if (isset($this->param['menu_id']) && $this->param['menu_id']) {
            $menuModel = new AdminMenus();
            if ($menuModel::destroy(['menu_id' => $this->param['menu_id']])) {
                return Tools::ajaxReturn(true, '删除成功');
            } else {
                return Tools::ajaxReturn(false, '删除失败');
            }
        } else {
            return Tools::ajaxReturn(false, '删除失败');
        }
    }

    public function show()
    {
        if (isset($this->param['menu_id']) && $this->param['menu_id']) {
            AdminMenus::update(['is_show' => $this->param['is_show']], ['menu_id' => $this->param['menu_id']]);
            return Tools::ajaxReturn(true, '操作成功');
        } else {
            return Tools::ajaxReturn(false, '操作失败');
        }
    }

    public function getSonMenu()
    {
        if (isset($this->param['menu_id'])) {
            $sonMenuData = (new AdminMenus())->getList(['parent_id' => $this->param['menu_id']], 'menu_id, title')->toArray();
            return Tools::ajaxReturn(true, '', $sonMenuData);
        } else {
            return Tools::ajaxReturn(false);
        }
    }
}